package cn.school.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.school.mapper.SubjectsMapper;
import cn.school.mapper.TeacherMapper;
import cn.school.pojo.Subjects;
import cn.school.pojo.Teacher;
import cn.school.service.SubjectsService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
* @author Lenovo
* @description 针对表【subjects(科目表)】的数据库操作Service实现
* @createDate 2025-06-09 18:41:20
*/
@Service
public class SubjectsServiceImpl extends ServiceImpl<SubjectsMapper, Subjects>
    implements SubjectsService {
    @Resource
    private SubjectsMapper subjectsMapper;
    @Resource
    private TeacherMapper teacherMapper;
    @Override
    public String addSubjects(String subName, HttpServletRequest request) {
        String token = request.getHeader("token");
        JWT jwt = JWTUtil.parseToken(token);
        String id = (String) jwt.getPayload("id");
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        if (teacher==null){
            return "您当前没有权限请先认证身份";
        }else {
            Subjects subjects = new Subjects();
            subjects.setId(IdUtil.getSnowflake(1,1).nextId());
            subjects.setSubjectName(subName);
            subjects.setIsDel(0);
            subjectsMapper.insert(subjects);
            return "添加的科目是:"+subName;
        }
    }

    @Override
    public List<Subjects> findList() {
        QueryWrapper<Subjects> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del",0);
        List<Subjects> subjects = subjectsMapper.selectList(queryWrapper);
        return subjects;
    }

    @Override
    public String deleteSubjects(String subId, HttpServletRequest request) {
        String token = request.getHeader("token");
        JWT jwt = JWTUtil.parseToken(token);
        String id = (String) jwt.getPayload("id");
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        if (teacher==null){
            return "您当前没有权限请先认证身份";
        }
        else {
            QueryWrapper<Subjects> subjectsQueryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id",subId);
            Subjects subjects = subjectsMapper.selectOne(subjectsQueryWrapper);
            if (subjects.getIsDel()==0){
                subjects.setIsDel(1);
                subjectsMapper.updateById(subjects);
                return "删除成功";
            }else{
                return "已经删除";
            }
        }
    }
}




